package org.example;



import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.client.RestTemplate;

//服务变更监听者  用于监听服务上下线的变更事件
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ServiceChangeListener {


    private String ip;
    private int port;

    //重写 equals hash方法 因为要去重
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        ServiceChangeListener other = (ServiceChangeListener) obj;
        return this.ip.equals(other.ip) && this.port == other.port;
    }

    @Override
    public int hashCode() {
        return ip.hashCode() ;
    }

    //服务监听者的通知方法 需要给这个监听者发http请求 远程通知   微小版的策略模式
    void onServiceChanged(ServiceChangeEvent event, RestTemplate restTemplate) {

        switch (event.getChangeType()) {
            case LOGIN:
                serviceLogin(event, restTemplate);
                break;
            case LOGOUT:
                serviceLogout(event, restTemplate);
                break;
        }

    }



    private void serviceLogin(ServiceChangeEvent event, RestTemplate restTemplate){
        System.out.println("发送服务上线通知: " + event.getServiceInstance().getServiceName());
        try {
            restTemplate.postForObject("http://" + ip + ":" + port + "/notifyLogin", event, Void.class);
        }catch (Exception e){
            System.out.println("服务上线通知失败: " + e.getMessage());
        }
    }
    private void serviceLogout(ServiceChangeEvent event, RestTemplate restTemplate){
        System.out.println("发送服务下线通知: " + event.getServiceInstance().getServiceName());
        try {
            restTemplate.postForObject("http://" + ip + ":" + port + "/notifyLogout", event, Void.class);
        }catch (Exception e){
            System.out.println("服务下线通知失败: " + e.getMessage());
        }
    }
}
